package com.woniu.common.utils;
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
public class QRCodeTest{
    /*定义二维码的宽度和高度*/
    private static int WIDTH=300;
    private static int HEIGHT=300;
    private static String FORMAT="png";//二维码图片的格式

    //生成二维码
    public static void generateQRCode(File file,String content){
        //定义二维码的一些参数
        Map<EncodeHintType,Object>hints=new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET,"utf-8");//设置编码
        hints.put(EncodeHintType.ERROR_CORRECTION,ErrorCorrectionLevel.M);//设置容错的等级
        hints.put(EncodeHintType.MARGIN,2);//设置边距默认为5

        try{
            BitMatrix bitMatrix=new MultiFormatWriter().encode(content,BarcodeFormat.QR_CODE,WIDTH,HEIGHT,hints);
            //提醒一下：二维码并不单单指QRcode，其他的形式也可以类似的生成
            Path path=file.toPath();
            MatrixToImageWriter.writeToPath(bitMatrix,FORMAT,path);//写下指定的路径
        }catch(Exception e) {
            e.printStackTrace();
        }
    }
    //读取二维码
    public static void readQrCode(File file){
        MultiFormatReader reader=new MultiFormatReader();
        try{
            BufferedImage image=ImageIO.read(file);
            BinaryBitmap binaryBitmap=new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
            Map<DecodeHintType,Object>hints=new HashMap<>();
            hints.put(DecodeHintType.CHARACTER_SET,"utf-8");//设置编码
            Result result=reader.decode(binaryBitmap,hints);
            System.out.println("解析结果为："+result.toString());
            System.out.println("二维码的格式为"+result.getBarcodeFormat());
            System.out.println("二维码的文本内容为："+result.getText());
        }catch(Exception e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        generateQRCode(new File("Garycode.png"),"啊啊啊啊");
        readQrCode(new File("Garycode.png"));
        //readQrCode(new File("Garycode.jpg"));
    }
}

